package org.apache.ibatis.lgtest.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author lg
 * @description
 * @create 2019-07-25
 **/
public class CarDaoImpl implements CarDao {

  @Override
  public void getCarCode() {
    System.out.println("car code : 3333");
  }

  public static void main(String[] args) {
    //生成的代理类保存到磁盘
    System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
    CarDao carDaoProxy = (CarDao) Proxy.newProxyInstance(CarDaoImpl.class.getClassLoader(), new Class[]{CarDao.class}, new MyInvocationHandler(new CarDaoImpl()));
    carDaoProxy.getCarCode();
  }
}

interface CarDao {
  void getCarCode();
}

class MyInvocationHandler implements InvocationHandler {

  private CarDaoImpl carDao;

  public MyInvocationHandler() {

  }

  public MyInvocationHandler(CarDaoImpl carDao) {
    this.carDao = carDao;
  }

  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    System.out.println("call method " + method.getName() + " before");
    Object res = method.invoke(carDao, args);
    System.out.println("call method " + method.getName() + " end");
    return res;
  }
}
